package com.windgo.service;

import com.windgo.bean.*;
import com.windgo.bean.bo.*;
import com.windgo.bean.vo.*;
import com.windgo.mapper.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author doublec
 * @since 2022/10/14 09:54
 */
@Service
public class WxCartServiceImpl implements WxCartService {
    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketSystemMapper marketSystemMapper;
    @Autowired
    MarketGrouponMapper marketGrouponMapper;
    @Autowired
    MarketGrouponRulesMapper marketGrouponRulesMapper;
    @Autowired
    MarketOrderMapper marketOrderMapper;
    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    @Override
    public WxCartIndexVO indexCart(Integer userId) {
        WxCartIndexVO wxCartIndexVO = new WxCartIndexVO();
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(userId);
        List<MarketCart> list = marketCartMapper.selectByExample(marketCartExample);
        if (list.size() != 0) {
            List<MarketCart> innerList = marketCartMapper.selectByExample(marketCartExample);
            //如果productId是一样的，返回到购物车只是数量增加
            List<MarketCart> marketCartList = new ArrayList<>();
            List<Integer> productIds = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                MarketCart cart = list.get(i);
                Integer cartProductId = cart.getProductId();
                if (!productIds.contains(cartProductId)) {
                    productIds.add(cartProductId);
                    for (int j = i + 1; j < innerList.size(); j++) {
                        MarketCart marketCart = innerList.get(j);
                        Integer marketCartProductId = marketCart.getProductId();
                        if (cartProductId == marketCartProductId) {
                            Short number1 = cart.getNumber();
                            Short number = marketCart.getNumber();
                            cart.setNumber((short) (number1 + number));
                        }
                    }
                    marketCartList.add(cart);
                }
            }
            wxCartIndexVO.setCartList(marketCartList);
            boolean deleted = false;
            WxCartIndexInnerTotalVO indexInnerTotalVO = marketCartMapper.queryTotalInfo(userId, false, deleted);
            Integer checkedCount = marketCartMapper.queryCheckedGoodsInfo(userId, true, deleted);
            if (checkedCount == null) {
                indexInnerTotalVO.setCheckedGoodsCount(0);
            } else {
                indexInnerTotalVO.setCheckedGoodsCount(checkedCount);
            }
            Double checkedAccount = marketCartMapper.queryCheckedAmountInfo(userId, true, deleted);
            if (checkedAccount == null) {
                checkedAccount = 0.00;
                indexInnerTotalVO.setCheckedGoodsAmount(checkedAccount);
            } else {
                indexInnerTotalVO.setCheckedGoodsAmount(checkedAccount);
            }

            wxCartIndexVO.setCartTotal(indexInnerTotalVO);
            return wxCartIndexVO;
        }
        wxCartIndexVO.setCartList(new ArrayList<>());
        wxCartIndexVO.setCartTotal(new WxCartIndexInnerTotalVO(0, 0, 0.0, 0.0));
        return wxCartIndexVO;
    }

    @Override
    public int addCart(Integer userId, MarketCart marketCart) {
        Integer productId = marketCart.getProductId();
        Short buyNumber = marketCart.getNumber();
        Integer count;
        List<Integer> sqlProductIds = marketCartMapper.queryProductId(userId);
        if (sqlProductIds.contains(productId)){
            //判断该商品在购物车的状态如果是delete是1
            boolean deleted = marketCartMapper.queryDeleted(userId,productId);
            //如果是1，那么改状态为1，修改数量为buyNumber
            if (deleted == true){
                marketCartMapper.updateDeletedCart(productId, userId, buyNumber);
                marketCartMapper.updateNowCart(productId, userId);
            }else {
                //如果不是1，直接添加数量
                marketCartMapper.updateNumber(productId, userId, buyNumber);
                marketCartMapper.updateNowCart(productId, userId);
            }
            count = marketCartMapper.queryCartNum(userId);
        }else {
            //查询goods信息
            Integer goodsId = marketCart.getGoodsId();
            MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
            MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
            criteria.andIdEqualTo(goodsId);
//        MarketGoods marketGoods = (MarketGoods) marketGoodsMapper.selectByExample(marketGoodsExample);
            List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
            MarketGoods goods = marketGoods.get(0);

            //查询product信息
            MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
            MarketGoodsProductExample.Criteria criteria1 = marketGoodsProductExample.createCriteria();
            criteria1.andIdEqualTo(productId);
            criteria1.andGoodsIdEqualTo(goodsId);
//        MarketGoodsProduct marketGoodsProducts = (MarketGoodsProduct) marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
            List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
            MarketGoodsProduct goodsProduct = marketGoodsProducts.get(0);
            //商品的数量减去number
            marketGoodsProductMapper.updateNumber(productId, buyNumber);

            //加入到购物车
            marketCart.setId(null);
            marketCart.setSpecifications(goodsProduct.getSpecifications());
            marketCart.setUserId(userId);
            marketCart.setGoodsSn(goods.getGoodsSn());
            marketCart.setGoodsName(goods.getName());
            marketCart.setPrice(goodsProduct.getPrice());
            marketCart.setChecked(true);
            marketCart.setDeleted(false);
            marketCart.setPicUrl(goods.getPicUrl());
            marketCartMapper.insertSelective(marketCart);
            marketCartMapper.updateCart(marketCart.getId());
            count = marketCartMapper.queryCartNum(userId);
        }
        if (count == null){
            count = 0;
        }
        return count;
    }

    @Override
    public int queryGoodsNumberById(Integer goodsId) {
        int number = marketGoodsProductMapper.queryGoodsNumber(goodsId);
        return number;
    }

    @Override
    public int fastAddCart(Integer userId, MarketCart marketCart) {
        Integer productId = marketCart.getProductId();
        Short buyNumber = marketCart.getNumber();
        Integer cartId;
        List<Integer> sqlProductIds = marketCartMapper.queryProductId(userId);
        if (sqlProductIds.contains(productId)){
            //判断该商品在购物车的状态如果是delete是1
            boolean deleted = marketCartMapper.queryDeleted(userId,productId);
            //如果是1，那么改状态为1，修改数量为buyNumber
            if (deleted == true){
                marketCartMapper.updateDeletedCart(productId, userId, buyNumber);
                marketCartMapper.updateNowCart(productId, userId);
            }else {
                //如果不是1，直接添加数量
                marketCartMapper.updateNumber(productId, userId, buyNumber);
                marketCartMapper.updateNowCart(productId, userId);
            }
            cartId = marketCartMapper.queryCartId(userId,productId);
        }else {
            //查询goods信息
            Integer goodsId = marketCart.getGoodsId();
            MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
            MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
            criteria.andIdEqualTo(goodsId);
//        MarketGoods marketGoods = (MarketGoods) marketGoodsMapper.selectByExample(marketGoodsExample);
            List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
            MarketGoods goods = marketGoods.get(0);

            //查询product信息
            MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
            MarketGoodsProductExample.Criteria criteria1 = marketGoodsProductExample.createCriteria();
            criteria1.andIdEqualTo(productId);
            criteria1.andGoodsIdEqualTo(goodsId);
//        MarketGoodsProduct marketGoodsProducts = (MarketGoodsProduct) marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
            List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
            MarketGoodsProduct goodsProduct = marketGoodsProducts.get(0);
            String[] specifications = goodsProduct.getSpecifications();
            String newSpecification = specifications.toString();
            //商品的数量减去number
            marketGoodsProductMapper.updateNumber(productId, buyNumber);

            //快速购买——>加入到购物车，返回购物车id
            //加入到购物车
            marketCart.setId(null);
            marketCart.setSpecifications(goodsProduct.getSpecifications());
            marketCart.setUserId(userId);
            marketCart.setGoodsSn(goods.getGoodsSn());
            marketCart.setGoodsName(goods.getName());
            marketCart.setPrice(goodsProduct.getPrice());
            marketCart.setChecked(true);
            marketCart.setDeleted(false);
            marketCart.setPicUrl(goods.getPicUrl());
            marketCartMapper.insertSelective(marketCart);
            marketCartMapper.updateCart(marketCart.getId());
            cartId = marketCart.getId();
        }
        return cartId;
    }

    @Override
    public WxCartIndexVO deleteCart(Integer userId, CartDeleteBO cartDeleteBO) {
        //先进行逻辑的删除
        List<Integer> productIds = cartDeleteBO.getProductIds();
        for (Integer productId : productIds) {
            //通过productId和userId获取到购物车的详细信息
            MarketCart marketCart = marketCartMapper.selectByProductIdAndUserId(productId, userId);
            //market_goods_product的数量加number（通过productId）
            marketGoodsProductMapper.addNumberByProductId(productId, marketCart);
            //逻辑删除
            marketCartMapper.deleteByProductId(userId, productId);
            marketCartMapper.updateNowCart(productId, userId);
        }
        WxCartIndexVO wxCartIndexVO = new WxCartIndexVO();
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(userId);
        List<MarketCart> list = marketCartMapper.selectByExample(marketCartExample);
        wxCartIndexVO.setCartList(list);
        boolean deleted = false;
        WxCartIndexInnerTotalVO indexInnerTotalVO = marketCartMapper.queryTotalInfo(userId, false, deleted);
        Integer checkedCount = marketCartMapper.queryCheckedGoodsInfo(userId, true, deleted);
        if (indexInnerTotalVO == null){
            WxCartIndexInnerTotalVO indexInnerTotalVO1 = new WxCartIndexInnerTotalVO();
            if (checkedCount == null) {
                indexInnerTotalVO1.setCheckedGoodsCount(0);
            }
            Double checkedAccount = marketCartMapper.queryCheckedAmountInfo(userId, true, deleted);
            if (checkedAccount == null) {
                indexInnerTotalVO1.setCheckedGoodsAmount(0.0);
            }else {
                indexInnerTotalVO1.setCheckedGoodsAmount(checkedAccount);
            }
            wxCartIndexVO.setCartTotal(indexInnerTotalVO1);
        }else {
            if (checkedCount == null) {
                indexInnerTotalVO.setCheckedGoodsCount(0);
            } else {
                indexInnerTotalVO.setCheckedGoodsCount(checkedCount);
            }
            Double checkedAccount = marketCartMapper.queryCheckedAmountInfo(userId, true, deleted);
            if (checkedAccount == null) {
                indexInnerTotalVO.setCheckedGoodsAmount(0.0);
            } else {
                indexInnerTotalVO.setCheckedGoodsAmount(checkedAccount);
            }
            wxCartIndexVO.setCartTotal(indexInnerTotalVO);
        }
        return wxCartIndexVO;
    }

    @Override
    public WxCartIndexVO checkedCart(Integer userId, CartCheckedBO cartCheckedBO, boolean b) {
        List<Integer> productIds = cartCheckedBO.getProductIds();
        //修改cart中product_id为数组里面值的checked为true
        for (Integer productId : productIds) {
            marketCartMapper.updateCheckedByProductId(userId, productId, b);
        }
        WxCartIndexVO wxCartIndexVO = new WxCartIndexVO();
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(userId);
        List<MarketCart> list = marketCartMapper.selectByExample(marketCartExample);
        List<MarketCart> innerList = marketCartMapper.selectByExample(marketCartExample);
        //如果productId是一样的，返回到购物车只是数量增加
        List<MarketCart> marketCartList = new ArrayList<>();
        List<Integer> productIds1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            MarketCart cart = list.get(i);
            Integer cartProductId = cart.getProductId();
            if (!productIds1.contains(cartProductId)) {
                productIds1.add(cartProductId);
                for (int j = i + 1; j < innerList.size(); j++) {
                    MarketCart marketCart = innerList.get(j);
                    Integer marketCartProductId = marketCart.getProductId();
                    if (cartProductId == marketCartProductId) {
                        Short number1 = cart.getNumber();
                        Short number = marketCart.getNumber();
                        cart.setNumber((short) (number1 + number));
                    }
                }
                marketCartList.add(cart);
            }
        }
        wxCartIndexVO.setCartList(marketCartList);
        //wxCartIndexVO.setCartList(list);
        boolean deleted = false;
        WxCartIndexInnerTotalVO indexInnerTotalVO = marketCartMapper.queryTotalInfo(userId, false, deleted);
        Integer checkedCount = marketCartMapper.queryCheckedGoodsInfo(userId, true, deleted);
        if (checkedCount == null) {
            indexInnerTotalVO.setCheckedGoodsCount(0);
        } else {
            indexInnerTotalVO.setCheckedGoodsCount(checkedCount);
        }
        Double checkedAccount = marketCartMapper.queryCheckedAmountInfo(userId, true, deleted);
        if (checkedAccount == null) {
            checkedAccount = 0.00;
            indexInnerTotalVO.setCheckedGoodsAmount(checkedAccount);
        } else {
            indexInnerTotalVO.setCheckedGoodsAmount(checkedAccount);
        }
        wxCartIndexVO.setCartTotal(indexInnerTotalVO);
        return wxCartIndexVO;
    }

    @Override
    public int updateCart(Integer userId, CartUpdateBO cartUpdateBO) {
        //查询原来cart表的数量
        int oldNum = marketCartMapper.queryCartOldNum(userId, cartUpdateBO);
        //修改cart表中的数量
        marketCartMapper.updateNumberById(userId, cartUpdateBO);
        //修改market_good_product表的数量
        Integer newNum = cartUpdateBO.getNumber();
        int fixNum = newNum - oldNum;
        marketGoodsProductMapper.updateFixNumber(fixNum, cartUpdateBO);
        marketCartMapper.updateNowCart(cartUpdateBO.getProductId(), userId);
        return 1;
    }

    @Override
    public Short goodsCountCart(Integer userId) {
        Short totalNumber = marketCartMapper.queryTotalNumberByUserId(userId);
        return totalNumber;
    }

    @Override
    public WxCartCheckoutVO checkoutCart(Integer userId, CartCheckoutBO cartCheckoutBO) {
        WxCartCheckoutVO wxCartCheckoutVO = new WxCartCheckoutVO();
        Integer cartId = cartCheckoutBO.getCartId();
        if (cartId == 0) {
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria cartExampleCriteria = marketCartExample.createCriteria();
            cartExampleCriteria.andCheckedEqualTo(true);
            cartExampleCriteria.andDeletedEqualTo(false);
            cartExampleCriteria.andUserIdEqualTo(userId);
            List<MarketCart> list = marketCartMapper.selectByExample(marketCartExample);
            List<MarketCart> innerList = marketCartMapper.selectByExample(marketCartExample);
            //如果productId是一样的，返回到购物车只是数量增加
            List<MarketCart> marketCartList = new ArrayList<>();
            List<Integer> productIds1 = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                MarketCart cart = list.get(i);
                Integer cartProductId = cart.getProductId();
                if (!productIds1.contains(cartProductId)) {
                    productIds1.add(cartProductId);
                    for (int j = i + 1; j < innerList.size(); j++) {
                        MarketCart marketCart = innerList.get(j);
                        Integer marketCartProductId = marketCart.getProductId();
                        if (cartProductId == marketCartProductId) {
                            Short number1 = cart.getNumber();
                            Short number = marketCart.getNumber();
                            cart.setNumber((short) (number1 + number));
                        }
                    }
                    marketCartList.add(cart);
                }
            }
            wxCartCheckoutVO.setCheckedGoodsList(marketCartList);
            //cartId
            wxCartCheckoutVO.setCartId(cartId);
            //goodsTotalPrice（单价*数量）
            Double goodsTotalPrice = 0.0;
            for (MarketCart marketCart : list) {
                int goodsNumber = marketCart.getNumber();
                double goodsPrice = marketCart.getPrice().doubleValue();
                goodsTotalPrice += (goodsNumber * goodsPrice);
                wxCartCheckoutVO.setGoodsTotalPrice(goodsTotalPrice);
            }
//            //可用优惠券
//            MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
//            MarketCouponUserExample.Criteria marketCouponUserExampleCriteria = marketCouponUserExample.createCriteria();
//            marketCouponUserExampleCriteria.andUserIdEqualTo(userId);
//            marketCouponUserExampleCriteria.andStatusEqualTo((short) 0);
//            marketCouponUserExampleCriteria.andStartTimeLessThanOrEqualTo(new Date());
//            marketCouponUserExampleCriteria.andEndTimeGreaterThanOrEqualTo(new Date());
//            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
//            //int availableCouponLength = marketCouponUserMapper.queryAvailableCoupon(userId);
//            wxCartCheckoutVO.setAvailableCouponLength(marketCouponUsers.size());

            //couponId
            wxCartCheckoutVO.setCouponId(cartCheckoutBO.getCouponId());

            //couponPrice
            MarketCouponExample marketCouponExample = new MarketCouponExample();
            MarketCouponExample.Criteria marketCouponExampleCriteria = marketCouponExample.createCriteria();
            marketCouponExampleCriteria.andIdEqualTo(cartCheckoutBO.getCouponId());
            marketCouponExampleCriteria.andMinLessThanOrEqualTo(BigDecimal.valueOf(goodsTotalPrice));
            List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
            //double couponDiscount = marketCoupons.getDiscount().doubleValue();
            Double couponDiscount = 0.0;
            if (marketCoupons.size() == 0) {
                wxCartCheckoutVO.setCouponPrice(couponDiscount);
            } else {
                //MarketCoupon marketCouponInfo = null;
                for (MarketCoupon marketCoupon : marketCoupons) {

                    couponDiscount = marketCoupon.getDiscount().doubleValue();
                    wxCartCheckoutVO.setCouponPrice(couponDiscount);

                }
            }
            //优惠券
            Integer couponSize = 0;
            MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
            MarketCouponUserExample.Criteria marketCouponUserExampleCriteria = marketCouponUserExample.createCriteria();
            marketCouponUserExampleCriteria.andUserIdEqualTo(userId);
            marketCouponUserExampleCriteria.andStatusEqualTo((short) 0);
            marketCouponUserExampleCriteria.andStartTimeLessThanOrEqualTo(new Date());
            marketCouponUserExampleCriteria.andEndTimeGreaterThanOrEqualTo(new Date());
            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
            for (MarketCouponUser marketCouponUser : marketCouponUsers) {
                Integer couponId = marketCouponUser.getCouponId();
                BigDecimal minValue = marketCouponMapper.queryMinValueById(couponId);
                double min = minValue.doubleValue();
                if (goodsTotalPrice > min){
                    couponSize++;
                }
            }
            wxCartCheckoutVO.setAvailableCouponLength(couponSize);

            //grouponPrice
            MarketGrouponRulesExample marketGrouponRulesExample = new MarketGrouponRulesExample();
            MarketGrouponRulesExample.Criteria marketGrouponRulesExampleCriteria = marketGrouponRulesExample.createCriteria();
            marketGrouponRulesExampleCriteria.andIdEqualTo(cartCheckoutBO.getGrouponRulesId());
            List<MarketGrouponRules> marketGrouponRules = marketGrouponRulesMapper.selectByExample(marketGrouponRulesExample);
            Double groupDiscount = 0.0;
            if (marketGrouponRules.size() == 0) {
                wxCartCheckoutVO.setGrouponPrice(groupDiscount);
            } else {
                MarketGrouponRules marketGrouponRulesInfo = null;
                for (MarketGrouponRules marketGrouponRule : marketGrouponRules) {
                    marketGrouponRulesInfo = marketGrouponRule;
                }
                BigDecimal discount = marketGrouponRulesInfo.getDiscount();
                if (discount == null) {
                    wxCartCheckoutVO.setGrouponPrice(groupDiscount);
                } else {
                    groupDiscount = marketGrouponRulesInfo.getDiscount().doubleValue();
                    wxCartCheckoutVO.setGrouponPrice(groupDiscount);
                }
            }
            //grouponRulesId
            wxCartCheckoutVO.setGrouponRulesId(cartCheckoutBO.getGrouponRulesId());
            //userCouponId
            wxCartCheckoutVO.setUserCouponId(cartCheckoutBO.getUserCouponId());
            //运费（先判断是否达到满减金额）达到为0元，没达到要运费
            //运费金额
            List<MarketSystem> marketSystemList = marketSystemMapper.selectAllInfoFromSystemTable();
            Double freightMin = 0.00;
            Double freightValue = 0.00;
            for (MarketSystem marketSystem : marketSystemList) {
                if (marketSystem.getKeyName().equals("market_express_freight_min")) {
                    String freight_min = marketSystem.getKeyValue();
                    freightMin = Double.parseDouble(freight_min);
                } else if (marketSystem.getKeyName().equals("market_express_freight_value")) {
                    String freight_value = marketSystem.getKeyValue();
                    freightValue = Double.parseDouble(freight_value);
                }
            }
            Double orderTotalPrice = 0.00;
            if (goodsTotalPrice < freightMin) {
                wxCartCheckoutVO.setFreightPrice(freightValue);
                orderTotalPrice = goodsTotalPrice + freightValue - couponDiscount - groupDiscount;
            } else {
                wxCartCheckoutVO.setFreightPrice(0.00);
                orderTotalPrice = goodsTotalPrice - couponDiscount - groupDiscount;
            }
            //actualPrice
            wxCartCheckoutVO.setActualPrice(orderTotalPrice);

            //orderTotalPrice
            wxCartCheckoutVO.setOrderTotalPrice(orderTotalPrice);
        } else {
            //查询checkedGoodsList
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria cartExampleCriteria = marketCartExample.createCriteria();
            cartExampleCriteria.andIdEqualTo(cartId);
            cartExampleCriteria.andUserIdEqualTo(userId);
            List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample);
            MarketCart marketCartGoods = null;
            for (MarketCart marketCart : marketCartList) {
                marketCartGoods = marketCart;
            }
            wxCartCheckoutVO.setCheckedGoodsList(marketCartList);
            //cartId
            wxCartCheckoutVO.setCartId(cartId);
            //goodsTotalPrice（单价*数量）
            int goodsNumber = marketCartGoods.getNumber();
            double goodsPrice = marketCartGoods.getPrice().doubleValue();
            Double goodsTotalPrice = (goodsNumber * goodsPrice);
            wxCartCheckoutVO.setGoodsTotalPrice(goodsTotalPrice);
            //couponId
            wxCartCheckoutVO.setCouponId(cartCheckoutBO.getCouponId());

            //couponPrice
            MarketCouponExample marketCouponExample = new MarketCouponExample();
            MarketCouponExample.Criteria marketCouponExampleCriteria = marketCouponExample.createCriteria();
            marketCouponExampleCriteria.andIdEqualTo(cartCheckoutBO.getCouponId());
            marketCouponExampleCriteria.andMinLessThanOrEqualTo(BigDecimal.valueOf(goodsTotalPrice));
            List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
            //double couponDiscount = marketCoupons.getDiscount().doubleValue();
            Double couponDiscount = 0.0;
            if (marketCoupons.size() == 0) {
                wxCartCheckoutVO.setCouponPrice(couponDiscount);
            } else {
                //MarketCoupon marketCouponInfo = null;
                for (MarketCoupon marketCoupon : marketCoupons) {
                    couponDiscount = marketCoupon.getDiscount().doubleValue();
                    wxCartCheckoutVO.setCouponPrice(couponDiscount);

                }
            }
            //优惠券
            Integer couponSize = 0;
            MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
            MarketCouponUserExample.Criteria marketCouponUserExampleCriteria = marketCouponUserExample.createCriteria();
            marketCouponUserExampleCriteria.andUserIdEqualTo(userId);
            marketCouponUserExampleCriteria.andStatusEqualTo((short) 0);
            marketCouponUserExampleCriteria.andStartTimeLessThanOrEqualTo(new Date());
            marketCouponUserExampleCriteria.andEndTimeGreaterThanOrEqualTo(new Date());
            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
            for (MarketCouponUser marketCouponUser : marketCouponUsers) {
                Integer couponId = marketCouponUser.getCouponId();
                BigDecimal minValue = marketCouponMapper.queryMinValueById(couponId);
                double min = minValue.doubleValue();
                if (goodsTotalPrice > min){
                    couponSize++;
                }
            }
            wxCartCheckoutVO.setAvailableCouponLength(couponSize);

            //grouponPrice
            MarketGrouponRulesExample marketGrouponRulesExample = new MarketGrouponRulesExample();
            MarketGrouponRulesExample.Criteria marketGrouponRulesExampleCriteria = marketGrouponRulesExample.createCriteria();
            marketGrouponRulesExampleCriteria.andIdEqualTo(cartCheckoutBO.getGrouponRulesId());
            List<MarketGrouponRules> marketGrouponRules = marketGrouponRulesMapper.selectByExample(marketGrouponRulesExample);
            Double groupDiscount = 0.0;
            if (marketGrouponRules.size() == 0) {
                wxCartCheckoutVO.setGrouponPrice(groupDiscount);
            } else {
                MarketGrouponRules marketGrouponRulesInfo = null;
                for (MarketGrouponRules marketGrouponRule : marketGrouponRules) {
                    marketGrouponRulesInfo = marketGrouponRule;
                }
                BigDecimal discount = marketGrouponRulesInfo.getDiscount();
                if (discount == null) {
                    wxCartCheckoutVO.setGrouponPrice(groupDiscount);
                } else {
                    groupDiscount = marketGrouponRulesInfo.getDiscount().doubleValue();
                    wxCartCheckoutVO.setGrouponPrice(groupDiscount);
                }
            }
            //grouponRulesId
            wxCartCheckoutVO.setGrouponRulesId(cartCheckoutBO.getGrouponRulesId());

            //userCouponId
            wxCartCheckoutVO.setUserCouponId(cartCheckoutBO.getUserCouponId());
            //运费（先判断是否达到满减金额）达到为0元，没达到要运费
            //运费金额
            List<MarketSystem> marketSystemList = marketSystemMapper.selectAllInfoFromSystemTable();
            Double freightMin = 0.00;
            Double freightValue = 0.00;
            for (MarketSystem marketSystem : marketSystemList) {
                if (marketSystem.getKeyName().equals("market_express_freight_min")) {
                    String freight_min = marketSystem.getKeyValue();
                    freightMin = Double.parseDouble(freight_min);
                } else if (marketSystem.getKeyName().equals("market_express_freight_value")) {
                    String freight_value = marketSystem.getKeyValue();
                    freightValue = Double.parseDouble(freight_value);
                }
            }
            Double orderTotalPrice = 0.00;
            if (goodsTotalPrice < freightMin) {
                wxCartCheckoutVO.setFreightPrice(freightValue);
                orderTotalPrice = goodsTotalPrice + freightValue - couponDiscount - groupDiscount;
            } else {
                wxCartCheckoutVO.setFreightPrice(0.00);
                orderTotalPrice = goodsTotalPrice - couponDiscount - groupDiscount;
            }
            //actualPrice
            wxCartCheckoutVO.setActualPrice(orderTotalPrice);

            //orderTotalPrice
            wxCartCheckoutVO.setOrderTotalPrice(orderTotalPrice);
        }

        //查询checkedAddress
        Integer addressId = cartCheckoutBO.getAddressId();
        MarketAddressExample marketAddressExample = new MarketAddressExample();
        MarketAddressExample.Criteria marketAddressExampleCriteria = marketAddressExample.createCriteria();
        marketAddressExampleCriteria.andUserIdEqualTo(userId);
//      marketAddressExampleCriteria.andIsDefaultEqualTo(true);
        List<MarketAddress> marketAddresses = marketAddressMapper.selectByExample(marketAddressExample);
        //没有地址的时候
        if (marketAddresses.size() == 0) {
            WxCartCheckoutInnerAddressVO wxCartCheckoutInnerAddressVO1 = new WxCartCheckoutInnerAddressVO();
            wxCartCheckoutVO.setCheckedAddress(wxCartCheckoutInnerAddressVO1);
            wxCartCheckoutVO.setAddressId(0);
        } else {
            MarketAddressExample marketNewAddressExample = new MarketAddressExample();
            MarketAddressExample.Criteria marketNewAddressExampleCriteria = marketNewAddressExample.createCriteria();
            marketNewAddressExampleCriteria.andUserIdEqualTo(userId);
            marketNewAddressExampleCriteria.andIsDefaultEqualTo(true);
            List<MarketAddress> marketNewAddresses = marketAddressMapper.selectByExample(marketNewAddressExample);
            //有默认地址
            if (marketNewAddresses.size() != 0){
                MarketAddress marketAddress = marketNewAddresses.get(0);
                Integer id = marketAddress.getId();
                wxCartCheckoutVO.setAddressId(id);
                WxCartCheckoutInnerAddressVO wxCartCheckoutInnerAddressVO = marketAddressMapper.queryCheckedAddress(userId, id);
                wxCartCheckoutVO.setCheckedAddress(wxCartCheckoutInnerAddressVO);
            } else {
                //没有默认地址,如果addressId=0返回0
                if (addressId == 0) {
                    wxCartCheckoutVO.setAddressId(0);
                    WxCartCheckoutInnerAddressVO wxCartCheckoutInnerAddressVO = new WxCartCheckoutInnerAddressVO(0);
                    wxCartCheckoutVO.setCheckedAddress(wxCartCheckoutInnerAddressVO);
                }else{
                    //根据addressId查找地址
                    wxCartCheckoutVO.setAddressId(addressId);
                    WxCartCheckoutInnerAddressVO wxCartCheckoutInnerAddressVO = marketAddressMapper.queryCheckedAddress(userId, addressId);
                    //addressId
                    wxCartCheckoutVO.setCheckedAddress(wxCartCheckoutInnerAddressVO);
                }
            }
        }
        return wxCartCheckoutVO;
    }

    /**
     * 根据购物车下单
     *
     * @param wxOrderSubmitBo
     * @return
     */
    @Override
    //@Transactional
    public WxOrderSubmitVo wxSubmit(WxOrderSubmitBo wxOrderSubmitBo) {
        //创建响应体
        WxOrderSubmitVo data = new WxOrderSubmitVo();

        //获取cartId
        Integer cartId = wxOrderSubmitBo.getCartId();

        //从请求体中获取地址的id
        Integer addressId = wxOrderSubmitBo.getAddressId();

        //请求体中获取message
        String message = wxOrderSubmitBo.getMessage();

        //请求体中获取couponId
        Integer couponId = wxOrderSubmitBo.getCouponId();

        //请求体中获取userCouponId
        Integer userCouponId = wxOrderSubmitBo.getUserCouponId();

        //请求体中获取grouponRulesId
        Integer grouponRulesId = wxOrderSubmitBo.getGrouponRulesId();

        //获取当前登录的userId
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        MarketUser primaryPrincipal1 = (MarketUser) principals.getPrimaryPrincipal();
        Integer userId = primaryPrincipal1.getId();


        //创建订单对象
        MarketOrder order = new MarketOrder();
        //创建生成order_goods表的集合
        ArrayList<MarketOrderGoods> list = new ArrayList<>();

        //MarketOrderGoods orderGoods = new MarketOrderGoods();
        //TODO cartId=0的情况
        if (cartId == 0) {
            //根据userId去cart表中，查checked属性为1的情况
            MarketCartExample cartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andUserIdEqualTo(userId);
            List<MarketCart> carts = marketCartMapper.selectByExample(cartExample);

            //遍历循环获取checked=1的值   1是true
            for (MarketCart cart : carts) {
                Boolean checked = cart.getChecked();
                //checked为true时
                if (checked == true) {
                    //获取商品表的商品id
                    Integer goodsId = cart.getGoodsId();
                    //获取商品编号
                    String goodsSn = cart.getGoodsSn();
                    //获取商品名
                    String goodsName = cart.getGoodsName();
                    //获取商品货品的id
                    Integer productId = cart.getProductId();
                    //获取购买数量
                    //Short number = cart.getNumber();
                    Short number = cart.getNumber();
                    //获取价格
                    BigDecimal price = cart.getPrice();
                    //获取规格值列表
                    String[] specifications = cart.getSpecifications();
                    //获取商品图片
                    String picUrl = cart.getPicUrl();
                    //获取当前时间
                    Date date = new Date();
                    //创建order_goods对象,外面要创建order_goods的集合
                    MarketOrderGoods orderGoods = new MarketOrderGoods();
                    //TODO  差一个order_id
                    //orderGoods赋值
                    orderGoods.setGoodsId(goodsId);
                    orderGoods.setGoodsName(goodsName);
                    orderGoods.setGoodsSn(goodsSn);
                    orderGoods.setProductId(productId);
                    orderGoods.setNumber(number);
                    orderGoods.setPrice(price);
                    orderGoods.setSpecifications(specifications);
                    orderGoods.setPicUrl(picUrl);
                    orderGoods.setAddTime(date);


                    //TODO  生成订单
                    //创建订单对象
                    //MarketOrder order = new MarketOrder();

                    //根据addressId去address中获取信息
                    MarketAddress address = marketAddressMapper.selectByPrimaryKey(addressId);
                    //获取收货人姓名
                    String name = address.getName();
                    //获取手机号
                    String mobile = address.getTel();
                    //获取地址信息
                    String addressDetail = address.getAddressDetail();

                    //TODO  给订单信息赋值
                    order.setUserId(userId);
                    //生成随机数,订单编号随机生成
                    int i = (int) (Math.random() * 900000000) + 1000000000;
                    order.setOrderSn(i + "");
                    short a = 101;
                    order.setOrderStatus(a);
                    order.setConsignee(name);
                    order.setMobile(mobile);
                    order.setAddress(addressDetail);
                    order.setMessage(message);

                    //TODO 从cc的checkoutCart方法中获取
                    //创建checkoutCart()方法对应的形参
                    CartCheckoutBO cartCheckoutBO = new CartCheckoutBO();
                    cartCheckoutBO.setCartId(cartId);
                    cartCheckoutBO.setAddressId(addressId);
                    cartCheckoutBO.setCouponId(couponId);
                    cartCheckoutBO.setUserCouponId(userCouponId);
                    cartCheckoutBO.setGrouponRulesId(grouponRulesId);
                    //获取商品总费用
                    Double goodsTotalPrice = checkoutCart(userId, cartCheckoutBO).getGoodsTotalPrice();
                    //获取实付费用
                    Double actualPrice = checkoutCart(userId, cartCheckoutBO).getActualPrice();
                    //获取订单费用
                    Double orderTotalPrice = checkoutCart(userId, cartCheckoutBO).getOrderTotalPrice();
                    //获取团购减免
                    Double grouponPrice = checkoutCart(userId, cartCheckoutBO).getGrouponPrice();
                    //获取优惠减免
                    Double couponPrice = checkoutCart(userId, cartCheckoutBO).getCouponPrice();
                    //获取配送费用
                    Double freightPrice = checkoutCart(userId, cartCheckoutBO).getFreightPrice();

                    //TODO  继续给订单赋值
                    order.setGoodsPrice(BigDecimal.valueOf(goodsTotalPrice));
                    order.setFreightPrice(BigDecimal.valueOf(freightPrice));
                    order.setCouponPrice(BigDecimal.valueOf(couponPrice));
                    order.setIntegralPrice(BigDecimal.valueOf(0.00));
                    order.setGrouponPrice(BigDecimal.valueOf(grouponPrice));
                    //订单费用=总费用+运费-优惠券的减免
                    //BigDecimal orderPrice= BigDecimal.valueOf(goodsTotalPrice+freightPrice-couponPrice);
                    order.setOrderPrice(BigDecimal.valueOf(orderTotalPrice));
                    //实际费用=订单费用-用户积分减免
                    order.setActualPrice(BigDecimal.valueOf(actualPrice));
                    order.setAddTime(date);

                    //order_goods对象添加到集合中
                    list.add(orderGoods);
                    //TODO  生成订单后购物车里商品消失
                    cart.setDeleted(true);
                    marketCartMapper.updateByPrimaryKeySelective(cart);
                }
            }
            //生成订单
            marketOrderMapper.insertSelective(order);
            Integer orderId = order.getId();
            //对order_goods集合进行遍历，将orderId添加进
            for (MarketOrderGoods marketOrderGoods : list) {
                marketOrderGoods.setOrderId(orderId);
            }

            //生成订单和商品联系
            for (MarketOrderGoods marketOrderGoods : list) {
                marketOrderGoodsMapper.insertSelective(marketOrderGoods);
            }
            data.setOrderId(orderId);
            data.setGrouponLinkId(0);


            return data;
        }
        //cartId不为0的情况
        //TODO  不为0 ，就是立即购买的，立即购买只能进行单个购买
        //获取cartId,根据cartId去查cart表中的数据
        MarketCart marketCart = marketCartMapper.selectByPrimaryKey(cartId);


        //获取商品表的商品id
        Integer goodsId = marketCart.getGoodsId();
        //获取商品编号
        String goodsSn = marketCart.getGoodsSn();
        //获取商品名
        String goodsName = marketCart.getGoodsName();
        //获取商品货品的id
        Integer productId = marketCart.getProductId();
        //获取购买数量
        Short number = marketCart.getNumber();
        //获取价格
        BigDecimal price = marketCart.getPrice();
        //获取规格值列表
        String[] specifications = marketCart.getSpecifications();
        //获取商品图片
        String picUrl = marketCart.getPicUrl();
        //获取当前时间
        Date date = new Date();
        //创建order_goods对象,外面要创建order_goods的集合
        MarketOrderGoods orderGoods = new MarketOrderGoods();
        //TODO  差一个order_id
        //orderGoods赋值
        orderGoods.setGoodsId(goodsId);
        orderGoods.setGoodsName(goodsName);
        orderGoods.setGoodsSn(goodsSn);
        orderGoods.setProductId(productId);
        orderGoods.setNumber(number);
        orderGoods.setPrice(price);
        orderGoods.setSpecifications(specifications);
        orderGoods.setPicUrl(picUrl);
        orderGoods.setAddTime(date);
        //根据addressId去address中获取信息
        MarketAddress address = marketAddressMapper.selectByPrimaryKey(addressId);
        //获取收货人姓名
        String name = address.getName();
        //获取手机号
        String mobile = address.getTel();
        //获取地址信息
        String addressDetail = address.getAddressDetail();

        //TODO  给订单信息赋值
        order.setUserId(userId);
        //生成随机数,订单编号随机生成
        int i = (int) (Math.random() * 900000000) + 1000000000;
        order.setOrderSn(i + "");
        short a = 101;
        order.setOrderStatus(a);
        order.setConsignee(name);
        order.setMobile(mobile);
        order.setAddress(addressDetail);
        order.setMessage(message);

        //TODO 从cc的checkoutCart方法中获取
        //创建checkoutCart()方法对应的形参
        CartCheckoutBO cartCheckoutBO = new CartCheckoutBO();
        cartCheckoutBO.setCartId(cartId);
        cartCheckoutBO.setAddressId(addressId);
        cartCheckoutBO.setCouponId(couponId);
        cartCheckoutBO.setUserCouponId(userCouponId);
        cartCheckoutBO.setGrouponRulesId(grouponRulesId);
        //获取商品总费用
        Double goodsTotalPrice = checkoutCart(userId, cartCheckoutBO).getGoodsTotalPrice();
        //获取实付费用
        Double actualPrice = checkoutCart(userId, cartCheckoutBO).getActualPrice();
        //获取订单费用
        Double orderTotalPrice = checkoutCart(userId, cartCheckoutBO).getOrderTotalPrice();
        //获取团购减免
        Double grouponPrice = checkoutCart(userId, cartCheckoutBO).getGrouponPrice();
        //获取优惠减免
        Double couponPrice = checkoutCart(userId, cartCheckoutBO).getCouponPrice();
        //获取配送费用
        Double freightPrice = checkoutCart(userId, cartCheckoutBO).getFreightPrice();

        //TODO  继续给订单赋值
        order.setGoodsPrice(BigDecimal.valueOf(goodsTotalPrice));
        order.setFreightPrice(BigDecimal.valueOf(freightPrice));
        order.setCouponPrice(BigDecimal.valueOf(couponPrice));
        order.setIntegralPrice(BigDecimal.valueOf(0.00));
        order.setGrouponPrice(BigDecimal.valueOf(grouponPrice));
        //订单费用=总费用+运费-优惠券的减免
        //BigDecimal orderPrice= BigDecimal.valueOf(goodsTotalPrice+freightPrice-couponPrice);
        order.setOrderPrice(BigDecimal.valueOf(orderTotalPrice));
        //实际费用=订单费用-用户积分减免
        order.setActualPrice(BigDecimal.valueOf(actualPrice));
        order.setAddTime(date);


        //生成订单
        marketOrderMapper.insertSelective(order);
        Integer orderId = order.getId();
        //order_goods，将orderId添加进
        orderGoods.setOrderId(orderId);
        //生成订单和商品联系
        marketOrderGoodsMapper.insertSelective(orderGoods);
        data.setOrderId(orderId);
        data.setGrouponLinkId(0);
        return data;
    }
}
